import { Button, message, Modal, Tooltip } from 'antd'
import Icon, { CloseOutlined, DeleteOutlined, EditOutlined, RollbackOutlined } from '@ant-design/icons'

import { apiFileUpload } from '@oBiz/apis'
import { useBaseInfoBoundStore } from '../BaseInfo'
import { eventBus } from '../utils'
import { apiPublishRouteCheck, apiPublishRoutePublish } from './apis'
import { TCellParams } from './interface'
import { useBoundStore } from './store'
import SendIcon from '@/assets/icons/send.svg?react'
import styles from './styles.module.less'

export const CellAction = ({ value, data }: TCellParams<'publishId'>) => {
  const archiveFlag = useBaseInfoBoundStore(v => v.waybillInfo?.archiveFlag)
  const getBaseInfoData = useBaseInfoBoundStore(v => v.getData)

  const gridRef = useBoundStore(v => v.gridRef)
  const editingRowData = useBoundStore(v => v.editingRowData)
  const delPublishRoute = useBoundStore(v => v.delPublishRoute)
  const setEditingRowData = useBoundStore(v => v.setEditingRowData)
  const getData = useBoundStore(v => v.getData)

  if (value == null || !data) {
    return
  }

  if (data.markFlag === 1) {
    return <del className={styles.CellAction_del}>已删除</del>
  }

  if (archiveFlag === 1) {
    return
  }

  if (data.publishStatus === 1) {
    return (
      <Tooltip title="删除">
        <Button
          type="link"
          danger
          icon={<DeleteOutlined />}
          onClick={() => {
            Modal.confirm({
              title: '确认要删除吗？',
              onOk: () => delPublishRoute(value),
            })
          }}
        />
      </Tooltip>
    )
  }

  if (data.publishStatus === 0) {
    const draftRowData = data && data.publishId === editingRowData?.publishId ? editingRowData : null
    const otherRowEditing = !draftRowData && !!editingRowData
    return (
      <>
        {!draftRowData && (
          <Tooltip title={otherRowEditing ? '其它行正在编辑' : '发布前编辑'}>
            <Button
              type="link"
              icon={<EditOutlined />}
              disabled={otherRowEditing}
              onClick={() => {
                gridRef.current?.api?.ensureColumnVisible('fileList', 'auto') // 滚动至可视区
                setEditingRowData({ ...data })
              }}
            />
          </Tooltip>
        )}
        {!!draftRowData && (
          <Tooltip title="取消编辑">
            <Button type="link" icon={<RollbackOutlined />} onClick={() => setEditingRowData(null)} />
          </Tooltip>
        )}
        <Tooltip title={otherRowEditing ? '其它行正在编辑' : '发布'}>
          <Button
            type="link"
            icon={<Icon component={SendIcon} />}
            disabled={
              otherRowEditing ||
              (draftRowData ? !draftRowData.occurDate || !draftRowData.keepDate : !data.occurDate || !data.keepDate)
            }
            onClick={() => {
              const { publishId, occurDate, keepDate, fileList, draftFileList } = (draftRowData || data)!
              if (!occurDate || !keepDate) return
              let fileRes: GetPromiseValue<ReturnType<typeof apiFileUpload>>[] | null = null // 避免重复上传
              Modal.confirm({
                title: '确认要发布吗？',
                onOk: async () => {
                  const res = await apiPublishRouteCheck({ publishId, occurDate, keepDate })
                  if (res) {
                    const closeMsg = message.open({
                      type: 'error',
                      duration: 0,
                      content: (
                        <div className={styles.CellAction_errMsg}>
                          <b>发布失败！</b>
                          <div>以下占位符校验不通过，请在右侧“占位符”卡片进行编辑后再发布</div>
                          <div className={styles.CellAction_errMsg_keys}>{res.map(d => d.attrKey).join('、')}</div>
                          <Button
                            className={styles.CellAction_errMsg_close}
                            type="text"
                            icon={<CloseOutlined />}
                            onClick={() => closeMsg()}
                          />
                        </div>
                      ),
                    })
                    return
                  }
                  const files = [...(fileList || [])]
                  if (draftFileList?.length) {
                    if (!fileRes) {
                      // 上传新附件
                      fileRes = await Promise.all(
                        draftFileList.map(d =>
                          apiFileUpload({
                            file: d.fileUrl,
                            attachType: 1,
                          }),
                        ),
                      )
                    }
                    files.push(...fileRes)
                  }
                  // 发布
                  await apiPublishRoutePublish({
                    publishId,
                    occurDate: occurDate!,
                    keepDate: keepDate!,
                    fileList: files,
                  })
                  setEditingRowData(null) // 置空草稿数据
                  getData() // 刷新列表
                  getBaseInfoData() // 刷新其它
                  if (fileRes?.length) eventBus.emit('attachmentChanged')
                },
              })
            }}
          />
        </Tooltip>
      </>
    )
  }
}
